
let defualtOptions={
  method:"GET",
  header:{
    'Content-Type': 'application/json'
  },
  logger:true
}
class Request{
    constructor(options){
      Object.assign(this,defualtOptions,options);
      this.header= Object.assign({},defualtOptions.header,options.header);
    }
    request(options){
      options.url=this.baseUrl+"/"+options.url;
      options.header=Object.assign({},this.header,options.header);
      options.params=Object.assign({},this.params,options.params);
      return request.call(this,options);
    }
}
/**
 * 消除对象里面的空值项
 * @param {*} data 
 */
function removeNull(data){
  if(!data){
    return;
  }
  for (var key in data){
    if (data[key] === null) {
      delete data[key]
    }
  }
}
/**
 * 参数对象转换成URL的字符串
 * @param {*} params 
 */
function parameterUrlify(params){
  if(!params){
    return;
  }
  var items=[];
  for(var key in params){
    if(params[key]){
       items.push(key+"="+params[key]);
    }
  }
  return items.join("&");
}
/**
 * URL和参数合并
 * @param {String} url 
 * @param {*} params 
 */
function unionUrl(url,params){
  if(!params){
    return url;
  }
  let str_params=parameterUrlify(params);
  if(!str_params){
    return url;
  }
  if(url.indexOf("?")<0){
      return url+"?"+str_params;
  }
  return url+"&"+str_params;
}
let messages=[
  "==============>请求开始<==============",
  "==============>请求结束<==============",
];
Request.prototype.log=function(type,message,data){
    let url;
    if(type==0){
      url=message.url;
      this.begin&&this.begin(message);
    }
    else if(type==1){
      this.end&&this.end(message);
    }
    else{

    }
    if(this.logger){
      if(type<0){
        console.log("* "+message);
        if(data){
          console.log(data);
        }
      }
      else{
        console.log(messages[type]);
        if(url){
          console.log("* 请求地址："+url);
        }
      }
    }
}
function request (options) {
  let startTime=new Date();
  this.log(0,options);
  let _this=this;
  removeNull(options.data);
  let url=unionUrl(options.url,options.params);
  return new Promise((resolve, reject) => {
      let response,error;
      wx.request({
        url: url,
        method:options.method,
        header:options.header,
        data:options.data,
        success(res){
            response=res.data;
            let result=response;
            if(_this.result){
              result=_this.result(result);
            }
            if(res.statusCode<400){
              resolve(result);
            }
            else{
              error = res;
              reject(res);
            }
        },
        fail(err){
          error = err
          reject(err)
        },
        complete () {
          let timeSpan=(new Date()-startTime)/1000;
          if (!error) {
            _this.log(-1,'请求成功耗时： ('+timeSpan+'s)',response);
            _this.log(1,{success:true,data:response});
          } else {
            console.log(error);
            _this.log(-1,'请求失败['+error.statusCode+']：'+error.errMsg);
            _this.log(1,{success:true,data:{code:error.statusCode,msg:error.errMsg}});
          }
         
        }
      })
  })
}

export function createRequest(options){
  let _this= new Request(options);
  return {
    _this:_this,
    request:function(options){
      return _this.request(options);
    }
  } 
}